import { defineStore } from 'pinia'
import { authService } from '@/services/apiService'
import { stopTokenManager } from '@/utils/tokenManager'
import type { User } from '@/types/product'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户登录状态
    isLoggedIn: false,
    // 用户信息
    userInfo: {
      access: '',
      refresh: '',
      id: 0,
      username: '',
      avatar: '',
      email: '',
      level: 0
    } as User
  }),

  actions: {
    // 登录
    async login(userData: User) {
      this.isLoggedIn = true
      this.userInfo = {
        access: userData.access,
        refresh: userData.refresh,
        id: userData.id,
        username: userData.username,
        avatar: userData.avatar || '',
        email: userData.email || '',
        level: userData.level || 0
      }
    },

    // 登出
    async logout() {
      try {
        await authService.logout()
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        this.isLoggedIn = false
        this.userInfo = {
          id: 0,
          username: '',
          avatar: '',
          email: '',
          level: 0,
          access: '',
          refresh: ''
        }
        // 清除token
        localStorage.removeItem('access')
        localStorage.removeItem('refresh')
        localStorage.removeItem('refresh_token')  // 添加这一行
        localStorage.removeItem('userInfo')
        
        // 停止token管理器
        stopTokenManager()
      }
    },

    // 更新用户信息
    updateUserInfo(userInfo: Partial<User>) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },

    // 更新access token
    updateAccessToken(accessToken: string) {
      this.userInfo.access = accessToken
      // 同时更新localStorage中的token
      localStorage.setItem('access', accessToken)
    }
  },

  getters: {
    // 获取用户姓名
    userName: (state) => state.userInfo.username,
    // 获取用户头像
    userAvatar: (state) => state.userInfo.avatar,
    // 判断是否已登录
    isLogin: (state) => state.isLoggedIn
  }
})